package Client.ui;


import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.GridLayout;
import org.eclipse.wb.swing.FocusTraversalOnArray;

import Client.Controler.AppliManager;

import java.awt.Component;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MainWindow {

	private JFrame frame;
	private JTextField tfLogin;
	private JPasswordField tfPassword;
	private AppliManager appliManager;

	/**
	 * Create the application.
	 * @param appliManager 
	 */
	public MainWindow(AppliManager appliManager) {					
		this.appliManager = appliManager;
		
		initialize();
		frame.setVisible(true);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 290, 148);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new GridLayout(4, 2, 0, 0));
		frame.setTitle("Connection");
		
		JLabel lblVworld = new JLabel("VWorld");
		frame.getContentPane().add(lblVworld);
		
		JPanel panel = new JPanel();
		frame.getContentPane().add(panel);
		
		JLabel lblLogin = new JLabel("Login:");
		frame.getContentPane().add(lblLogin);
		
		tfLogin = new JTextField();
		frame.getContentPane().add(tfLogin);
		tfLogin.setColumns(10);
		
		JLabel lblNewLabel = new JLabel("Password:");
		frame.getContentPane().add(lblNewLabel);
		
		tfPassword = new JPasswordField();
		frame.getContentPane().add(tfPassword);
		tfPassword.setColumns(10);
		
		JButton btnCreateYourOwn = new JButton("Create your own");
		btnCreateYourOwn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				new CreateAvatarWindow(appliManager);
			}
		});
		frame.getContentPane().add(btnCreateYourOwn);
		
		JButton btnConnect = new JButton("Connect");
		btnConnect.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {				
				if(appliManager.connexion(tfLogin.getText(), new String(tfPassword.getPassword()))){
					frame.dispose();
				}else{
					JOptionPane.showMessageDialog(frame, "Error in login or password.", "Connection error", JOptionPane.ERROR_MESSAGE);
				}
				
			}
		});
		frame.getContentPane().add(btnConnect);
		frame.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{frame.getContentPane(), lblVworld, lblLogin}));
	}

}
